#%%
import pandas as pd
import requests
import datetime
import random
import json
import time
import asyncio
from rich import print

#%%
import sys
import os

path = r"D:/StockDatas/"
sys.path.append(path)
from OtherTools import filetool

#%%


def get_163ticker(code=300999, times="09:31:10", retry=5):
    header = {
        "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36",
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "en-US,en;q=0.5",
    }
    params = {
        "symbol": code,
        "end": times,  # 14:55:15
    }
    for i in range(retry):
        res = requests.get(
            "http://quotes.money.163.com/service/zhubi_ajax.html?symbol=300999",
            params=params,
            headers=header,
        )
        if res.status_code != 200:
            print()
            print("STATUS CODE:{}".format(res.status_code).center(60, "*"))

        elif res.status_code == 200:
            dic = res.content.decode(encoding="UTF-8")
            dic = json.loads(dic)
            dic = dic["zhubi_list"]
            newL = []
            for x in dic:
                temp = {}
                temp["code"] = "'" + str(code)
                temp["datetime"] = time.strftime(
                    "%Y-%m-%d %H:%M:%S", time.localtime(x["DATE"]["sec"])
                )
                temp["price"] = x["PRICE"]
                temp["change"] = x["PRICE_INC"]
                temp["volume"] = x["VOLUME_INC"]
                temp["amount"] = x["TURNOVER_INC"]
                temp["type"] = x["TRADE_TYPE"]
                newL.append(temp)
            _df = pd.DataFrame(newL)
            return _df
            
        t = (random.randint(1000, 600)) / 100
        print("sleep {}s".format(t), end="*")
        time.sleep(t)


async def Ticker_Main(code, ParthDic, mode="realtime"):
    """
    mode='realtime' or "" 空
    """
    await asyncio.sleep(0.3)
    today = time.strftime("%Y-%m-%d")
    date = time.strftime("%Y-%m-%d")
    MainDir = ParthDic["Main"]
    dirpath = MainDir + ParthDic["ticker"]
    start = "09:31:10"

    filetool.DirPathChick(dirpath)
    FilePath = dirpath + "{}.csv".format(code)
    compare_temp_now = 0
    kill = 0
    Ttemp_now = None
    while True:
        now = time.strftime("%H:%M")
        temp_now = int("".join(now.split(":")))
        if temp_now < 600:
            print("---", end="*")
            return
        elif temp_now < 915:
            print("{} 后开盘".format((915 - temp_now) / 100 * 60 * 60), end="*")
            await asyncio.sleep(300)
            continue
        print(code, end=" ")
        df = pd.DataFrame()
        if filetool.FileCheck(FilePath):
            mode = "recorver"
            df = pd.read_csv(FilePath)
            date = df.datetime.iloc[-1]
            date = date.split(" ")[0]
            if date == today:
                start = df.datetime.iloc[-1].split(" ")[-1]
                Ttemp_now = int("".join(start.split(":")))
                print(start, Ttemp_now, "if filetool.FileCheck(FilePath):")
                if Ttemp_now == compare_temp_now:
                    print("retrying", kill)
                    if kill == 5:
                        return
                    kill += 1
                temp_now = Ttemp_now
                compare_temp_now = Ttemp_now
                if 1300 >= temp_now >= 1128 or 130000 >= temp_now >= 112930:
                    start = "13:00:00"
                elif temp_now > 150000:
                    print()
                    print("done".center(60, "*"))
                    return

        else:
            print("new file ==> {}".format(FilePath), end="*")
        sleeptime = (random.randint(600, 1000)) / 100

        nowtimes = str(
            datetime.datetime.strptime(today + " " + start, "%Y-%m-%d %H:%M:%S")
            + datetime.timedelta(minutes=(random.randint(25, 40)) / 10)
        ).split(" ")[-1]

        if int("".join(nowtimes.split(":"))) > int(
            "".join(time.strftime("%H:%M:%S").split(":"))
        ):
            # print("<<realtime start>>".center(60, " "))
            mode = "realtime"

        if mode == "realtime":
            await asyncio.sleep(0.1)
            sleeptime = random.randint(600, 1200) / 10
            if Ttemp_now != None and Ttemp_now != temp_now:
                if Ttemp_now < temp_now * 100 - 300:
                    temp_now = Ttemp_now
                else:
                    temp_now = Ttemp_now
            print(temp_now, 130000 >= temp_now >= 112900)
            if 130000 >= temp_now >= 112900:
                sleeptime = 600
                mode = "recorver"
            elif temp_now > 150000 and today == df.datetime.iloc[-1].split(" ")[0]:
                mode = "recorver"
                print(temp_now, temp_now < 150000)
                print()
                print("未在交易时段,请尝试其他方法".center(60, "*"))
                return
            elif temp_now <= 150000:
                nowtimes = time.strftime("%H:%M:%S")

            else:
                print()
                print("request end time out for range".center(60, "*"))
        if 130000 >= int("".join(now.split(":"))) > 112900:
            sleeptime = 600

        print("mode:{}".format(mode), end=" ")
        print("from:{} {} to:{} {}".format(date, start, today, nowtimes), end=" ")
        _df = get_163ticker(code=code, times=nowtimes, retry=5)
        # times = _df.datetime.iloc[-1]

        df = pd.concat([df, _df])
        df.drop_duplicates("datetime", inplace=True)
        df.sort_values("datetime", inplace=True)
        df.to_csv(FilePath, index=False)
        print("sleep:{}".format(str(sleeptime)), end=" ")
        print("{} saved".format(FilePath))
        print(
            "price:{} amount:{}".format(df.price.iloc[-1], df.amount.iloc[-1]), end=" "
        )
        print("\n" * 2)
        print(time.strftime("%Y-%m-%d %H:%M:%S"))
        await asyncio.sleep(sleeptime)
        # time.sleep(sleeptime)


def get_163tickerLoop(
    codeL,
    ParthDic={
        "Main": "D:/StockDatas/",
        "basic": "basic/",
        "daily": "163_Daily_Bar/",
        "report": "Reports/",
        "temp": "temp/",
        "ticker": "History_ticker/",
        "mins": "History_mins/",
    },
    mode="",
):
    """
    mode='realtime' or "" 空
    ParthDic = {
        "Main": "D:/StockDatas/",
        "basic": "basic/",
        "daily": "163_Daily_Bar/",
        "report": "Reports/",
        "temp": "temp/",
        "ticker": "History_ticker/",
        "mins": "History_mins/",
    }
    """
    loop = asyncio.get_event_loop()
    tasks = [Ticker_Main(code, ParthDic, mode="") for code in codeL]
    loop.run_until_complete(asyncio.wait(tasks))
    # loop.close()


# %%
if __name__ == "__main__":
    ParthDic = {
        "Main": "D:/StockDatas/",
        "basic": "basic/",
        "daily": "163_Daily_Bar/",
        "report": "Reports/",
        "temp": "temp/",
        "ticker": "History_ticker/",
        "mins": "History_mins/",
    }
    codeL = ["300999", "000001", "601398", "600010", "601012", "000008"]
    get_163tickerLoop(codeL, ParthDic, mode="")
